// Comment.js - 评论模型
const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/db');

/**
 * 评论模型类
 * 映射数据库comments表，提供评论相关的数据访问和方法
 */
class Comment {
  constructor() {
    // 定义模型结构
    this.model = sequelize.define('Comment', {
      id: {
        type: DataTypes.BIGINT,
        primaryKey: true,
        autoIncrement: true
      },
      content: {
        type: DataTypes.TEXT,
        allowNull: false
      },
      like_count: {
        type: DataTypes.INTEGER,
        allowNull: false,
        defaultValue: 0
      },
      status: {
        type: DataTypes.INTEGER,
        allowNull: true,
        defaultValue: 1
      },
      user_id: {
        type: DataTypes.BIGINT,
        allowNull: false,
        references: {
          model: 'users',
          key: 'id'
        }
      },
      video_id: {
        type: DataTypes.BIGINT,
        allowNull: false,
        references: {
          model: 'videos',
          key: 'id'
        }
      },
      parent_id: {
        type: DataTypes.BIGINT,
        allowNull: true,
        references: {
          model: 'comments',
          key: 'id'
        }
      },
      created_at: {
        type: DataTypes.DATE,
        allowNull: false
      },
      updated_at: {
        type: DataTypes.DATE,
        allowNull: false
      },
      deleted_at: {
        type: DataTypes.DATE,
        allowNull: true
      }
    }, {
      tableName: 'comments',
      timestamps: false,
      paranoid: true,
      deletedAt: 'deleted_at',
      indexes: [
        {
          fields: ['video_id']
        },
        {
          fields: ['user_id']
        },
        {
          fields: ['parent_id']
        },
        {
          fields: ['like_count']
        }
      ]
    });
  }

  /**
   * 创建评论
   * @param {object} commentData - 评论数据
   * @returns {Promise<Object>} - 创建的评论
   */
  async create(commentData) {
    try {
      const now = new Date();
      const comment = await this.model.create({
        ...commentData,
        created_at: now,
        updated_at: now
      });
      return comment;
    } catch (error) {
      console.error('创建评论失败:', error);
      throw error;
    }
  }

  /**
   * 删除评论
   * @param {number} id - 评论ID
   * @param {number} userId - 用户ID（用于验证权限）
   * @returns {Promise<number>} - 删除的记录数
   */
  async destroy(id, userId) {
    try {
      const result = await this.model.destroy({
        where: {
          id: id,
          user_id: userId
        }
      });
      return result;
    } catch (error) {
      console.error('删除评论失败:', error);
      throw error;
    }
  }

  /**
   * 获取视频的评论列表
   * @param {number} videoId - 视频ID
   * @param {number} page - 页码
   * @param {number} pageSize - 每页数量
   * @returns {Promise<Array>} - 评论列表
   */
  async getVideoComments(videoId, page = 1, pageSize = 10) {
    try {
      const offset = (page - 1) * pageSize;
      const query = `
        SELECT 
          c.id, 
          c.content, 
          c.like_count, 
          c.status, 
          c.user_id, 
          c.video_id, 
          c.parent_id, 
          c.created_at, 
          c.updated_at,
          u.username, 
          u.nickname, 
          u.avatar
        FROM comments c
        LEFT JOIN users u ON c.user_id = u.id
        WHERE c.video_id = :videoId 
        AND c.status = 1
        AND c.parent_id IS NULL
        ORDER BY c.created_at DESC
        LIMIT :pageSize OFFSET :offset
      `;
      
      const comments = await sequelize.query(query, {
        replacements: { videoId, pageSize, offset },
        type: sequelize.QueryTypes.SELECT
      });
      
      // 获取回复
      for (const comment of comments) {
        const replies = await this.getReplies(comment.id);
        comment.replies = replies;
      }
      
      return comments;
    } catch (error) {
      console.error('获取视频评论失败:', error);
      throw error;
    }
  }

  /**
   * 获取评论的回复
   * @param {number} commentId - 评论ID
   * @returns {Promise<Array>} - 回复列表
   */
  async getReplies(commentId) {
    try {
      const query = `
        SELECT 
          c.id, 
          c.content, 
          c.like_count, 
          c.status, 
          c.user_id, 
          c.video_id, 
          c.parent_id, 
          c.created_at, 
          c.updated_at,
          u.username, 
          u.nickname, 
          u.avatar
        FROM comments c
        LEFT JOIN users u ON c.user_id = u.id
        WHERE c.parent_id = :commentId
        AND c.status = 1
        ORDER BY c.created_at ASC
      `;
      
      const replies = await sequelize.query(query, {
        replacements: { commentId },
        type: sequelize.QueryTypes.SELECT
      });
      
      return replies;
    } catch (error) {
      console.error('获取评论回复失败:', error);
      throw error;
    }
  }

  /**
   * 点赞评论
   * @param {number} commentId - 评论ID
   * @returns {Promise<number>} - 更新后的点赞数
   */
  async likeComment(commentId) {
    try {
      const result = await this.model.increment('like_count', {
        by: 1,
        where: { id: commentId }
      });
      
      // 获取更新后的点赞数
      const comment = await this.model.findByPk(commentId);
      return comment.like_count;
    } catch (error) {
      console.error('点赞评论失败:', error);
      throw error;
    }
  }

  /**
   * 获取视频的评论总数
   * @param {number} videoId - 视频ID
   * @returns {Promise<number>} - 评论总数
   */
  async getCommentsCount(videoId) {
    try {
      const count = await this.model.count({
        where: {
          video_id: videoId,
          status: 1,
          parent_id: null
        }
      });
      return count;
    } catch (error) {
      console.error('获取评论总数失败:', error);
      throw error;
    }
  }
}

module.exports = new Comment();